package cn.xinjiu.reggie.service.impl;

import cn.xinjiu.reggie.common.CustomException;
import cn.xinjiu.reggie.entity.Category;
import cn.xinjiu.reggie.entity.Dish;
import cn.xinjiu.reggie.entity.Setmeal;
import cn.xinjiu.reggie.mapper.CategoryMapper;
import cn.xinjiu.reggie.service.CategoryService;
import cn.xinjiu.reggie.service.DishService;
import cn.xinjiu.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by xinchen on 2022/7/4
 *
 * @Description : 分类服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * @param id 分类id
     * @return
     * @description 根据id删除分类信息，删除之前需要判断该分类下是否有子分类，如果有则不能删除
     */
    @Override
    public void remove(Long id) {

        // 查询当前分类是否已经关联菜品，若已关联则抛出异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper();
        // 添加查询条件，根据分类id匹配菜品
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        long count = dishService.count(dishLambdaQueryWrapper);
        if (count > 0) {
            // 已经关联菜品，抛出业务异常
            throw new CustomException("该分类下有菜品，不能删除");
        }

        // 查询当前分类是否已经关联套餐，若已关联则抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper();
        // 添加查询条件，根据分类id匹配套餐
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        long setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        if (setmealCount > 0) {
            // 已经关联套餐，抛出业务异常
            throw new CustomException("该分类下有套餐，不能删除");
        }

        // 正常删除当前分类
        super.removeById(id);
    }
}
